<template>
  <pro-form
    ref="formRef"
    :columns="columns"
    :data="detail"
    :actions="actions"
    class="add-project"
    :label-width="85"
    :style="{ '--item-content-width': '700px' }"
  >
    <template #organizeName>
      <el-tree-select
        collapse-tags
        collapse-tags-tooltip
        v-model="detail.organizeName"
        :data="treeData"
        show-checkbox
        check-strictly
        :props="{ label: 'orgName' }"
        node-key="orgCode"
        ref="treeSelectRef"
        :default-expand-all="true"
        :multiple="false"
      />
    </template>
  </pro-form>
</template>

<script setup lang="ts">
import api from '@/api';
import router from '@/router';
import { Column, ProForm } from '@jl/element-plus';
import { ElMessage, Resolve } from 'element-plus';
import { getOrganizationTree, getLicensedFirstCompany } from '@/api/project/index';

interface Props {
  isDialog?: boolean;
  editData?: any;
  onOk?: () => Promise<void>;
  onCancel?: () => Promise<void>;
}

const props = withDefaults(defineProps<Props>(), { isDialog: false });
const $route = useRoute();
const id = computed(() => Number($route.query.id));
const loading = ref(false);
const formRef = ref<InstanceType<typeof ProForm>>();
const detail = ref({});
const regionList = ref<any>([]);
const groupList = ref<any>([]);
const orgList = ref<any>([]);
const appId = process.env.VUE_APP_ID;

watch(
  () => props.editData,
  (value) => {
    detail.value = value
      ? {
          ...value,
          area: [Number(value.provinceCode), Number(value.cityCode), Number(value.areaCode)],
          organizeName: value.companyCode ? value.orgCode ?? value.companyCode + '+company' : '',
        }
      : {};
  },
  { immediate: true }
);

const treeData = computed(() => {
  const data =
    groupList.value?.map((group: any) => ({
      orgName: group.companyName,
      orgCode: group.companyCode + '+company',
      id: group.id,
      data: group,
      type: 'company',
      children: orgList.value?.rows
        ? JSON.parse(JSON.stringify(orgList.value?.rows))
            ?.filter((org: any) => org.companyCode === group.companyCode && org.appId === appId)
            .map((el: any) => ({ ...el, parentCode: el.companyCode }))
        : undefined,
    })) ?? [];
  return data;
});
onMounted(() => {
  if (appId) {
    getLicensedFirstCompany().then((res: any) => {
      groupList.value = [res];
    });
    getOrganizationTree({ appId }).then((res: any) => {
      orgList.value = res;
    });
  }
});

const columns = computed<Column[]>(() => {
  const columns: Column[] = [
    {
      type: 'input',
      prop: 'projectCode',
      label: '项目编码',
      rules: [
        { required: true, message: '请输入项目编码' },
        {
          pattern: /^[a-zA-Z0-9@#$%^&+=]{0,20}$/g,
          message: '项目编码为20位以内数字+英文+特殊字符组成',
          trigger: ['blur'],
        },
      ],
    },
    {
      type: 'input',
      prop: 'projectName',
      label: '项目名称',
      required: true,
    },
    {
      type: 'slot',
      prop: 'organizeName',
      label: '企业名称',
      required: true,
    },
    {
      type: 'cascader',
      prop: 'area',
      label: '省/市/区',
      required: true,
      formProps: {
        props: {
          lazy: true,
          async lazyLoad(node: any, resolve: Resolve) {
            const { level } = node;
            if (!level) {
              const result = await api.common.getRegion({ parentRegionCode: level });
              regionList.value.push(...result);
              resolve(
                result.map((el: any) => ({
                  value: el.regionCode,
                  label: el.regionName,
                  data: el,
                }))
              );
            } else {
              const result = await api.common.getRegion({ parentRegionCode: node.value });
              regionList.value.push(...result);
              resolve(
                result.map((el: any) => ({
                  value: el.regionCode,
                  label: el.regionName,
                  leaf: level === 2,
                }))
              );
            }
          },
        },
      },
    },
  ];
  if (!props.isDialog) {
    columns.unshift({
      type: 'title',
      prop: 'title',
      label: id.value ? '编辑项目' : '新增项目',
    });
  }
  return columns;
});

const actions = computed(() => ({
  ok: { text: '确定', handler: onOk, loading: loading.value },
  cancel: { text: '取消', handler: onCancel },
}));

const onCancel = () => {
  if (props.isDialog) {
    props.onCancel?.();
    return;
  }
  router.push({
    path: $route.path.replace('/detail', '/list'),
    query: {},
  });
};

const onOk = async () => {
  const { values, error } = await formRef.value!.validate();
  if (error) return;
  const formData: any = {
    ...values,
    appId: appId,
  };
  loading.value = true;
  try {
    delete formData.area;
    formData.provinceCode = values.area[0];
    formData.provinceName = regionList.value.find(
      (el: any) => el.regionCode === values.area[0]
    )?.regionName;
    formData.cityCode = values.area[1];
    formData.cityName = regionList.value.find(
      (el: any) => el.regionCode === values.area[1]
    )?.regionName;
    formData.areaCode = values.area[2];
    formData.areaName = regionList.value.find(
      (el: any) => el.regionCode === values.area[2]
    )?.regionName;
    const arr = formData.organizeName.split('+');
    if (arr[1]) {
      formData.companyCode = arr[0];
      formData.orgCode = null;
    } else {
      // function findParent(data: any, id: any, result: any) {
      //   for (let item of data) {
      //     if (item.orgCode === id) {
      //       result.unshift(item.orgCode);
      //       return true;
      //     }
      //     if (item.children && item.children.length > 0) {
      //       let isFind = findParent(item.children, id, result);
      //       if (isFind) {
      //         result.unshift(item.orgCode);
      //         return true;
      //       }
      //     }
      //   }
      //   return false;
      // }
      // const result: any = [];
      // findParent(treeData.value, arr[0], result);
      // data.companyCode = result[0].split('+')[0];
      formData.companyCode = groupList.value[0].companyCode;
      formData.orgCode = arr[0];
    }
    delete formData.organizeName;
    if (formData?.id) {
      await api.project.updateProject(formData);
    } else {
      await api.project.addProject({ ...formData, status: 1 });
    }
    ElMessage.success('操作成功');
  } finally {
    loading.value = false;
    if (props.isDialog) {
      await props.onOk?.();
    }
  }
};
</script>

<style lang="less" scoped>
.add-project {
  :deep(.actions) {
    width: 100%;
    display: flex;
    justify-content: flex-end;
  }
}
</style>
